package BlogMybatis.blog.controller;


import BlogMybatis.blog.pojo.Comment;
import BlogMybatis.blog.pojo.User;
import BlogMybatis.blog.service.BlogService;
import BlogMybatis.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Brandt
 * @since 2020-06-07
 */
@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Value("${comment.avatar}")
    private String avatar;
    @Value("${admin.openid}")
    private String adminOpenid;

    //查看评论列表
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable("blogId") Long blogId, Model model){
        List<Comment> comments = commentService.listCommentByBlogId(blogId);
        model.addAttribute("comments",comments);
        return "blog :: commentList";
    }

    //新增评论
    @PostMapping("/comments")
    public String postComment(Comment comment, HttpSession session,Model model){
        Long blogId = comment.getBlogId();
        String loginStatus = (String) session.getAttribute("loginStatus");
        //判断当前登录状态是QQ还是GitHub
        if(loginStatus != null){
            String avatar = (String) session.getAttribute("avatar");
            String openid = (String) session.getAttribute("openid");
            comment.setAvatar(avatar);
            comment.setAdminComment(1);
            //判断是否博主评论
            if(adminOpenid.equals(openid)){
                comment.setAdminComment(2);
            }
        }else {
            comment.setAvatar(avatar);
            comment.setAdminComment(0);
        }
        commentService.saveComments(comment);
        List<Comment> comments = commentService.listCommentByBlogId(blogId);
        model.addAttribute("comments",comments);
        return "blog :: commentList";
    }
}

